<template>
    <el-dialog v-model="dialogVisible" :title="form.Id != '' ? '修改' : '新增'" width="30%" :show-close="false" :center="true"
        draggable @close="$emit('closeAdd')">
        <el-form :model="form" label-width="80px" ref="ruleFormRef" :rules="rules">
            <el-form-item label="名称" prop="RoleName">
                <el-input v-model="form.RoleName" />
            </el-form-item>
            <el-form-item label="排序" prop="Order">
                <el-input v-model.number="form.Order" />
            </el-form-item>
            <el-form-item label="是否启用" prop="IsEnable">
                <el-switch v-model="form.IsEnable" />
            </el-form-item>
            <el-form-item label="描述" prop="Description">
                <el-input v-model="form.Description" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeAdd(ruleFormRef)">Cancel</el-button>
                <el-button type="primary" @click="save(ruleFormRef)">Confirm</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, watch } from 'vue'
import { FormInstance, FormRules } from 'element-plus'
import { addRole, editRole } from '../../../http/index'
import Role from '../../../class/Role'
const props = defineProps({
    isShow: Boolean,
    info: Role
})

const dialogVisible = computed(() => props.isShow)

const ruleFormRef = ref<FormInstance>()
const form = ref({
    Id: "",
    RoleName: "",
    Order: 0,
    IsEnable: false,
    Description: ""
})
watch(() => props.info, (newInfo: any) => {
    if (newInfo) {
        form.value = newInfo
    }
})

const rules = reactive<FormRules>({
    RoleName: [{ required: true, message: "请输入名称", trigger: 'blur' }],
    Order: [
        { required: true, message: "请输入一个序号" },
        { type: "number", message: "该字段必须是数字" }
    ]
})

const emits = defineEmits(["closeAdd", "success"])
const closeAdd = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    emits("closeAdd")
}
const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (form.value.Id) {
                editRole(form.value).then(function (res) {
                    if (res) {
                        emits("success", "修改成功!!!")
                    }
                })
            } else {
                addRole(form.value).then(function (res) {
                    if (res) {
                        emits("success", "修改成功!!!")
                    }
                })
            }
        } else {
            console.log("Add Or Edit Role error!!!", fields)
        }
    })
}
</script>

<style lang="scss" scoped></style>